package com.salesmanager.web.reference;

import com.salesmanager.core.utils.CacheUtils;
import com.salesmanager.core.utils.ajax.AjaxResponse;
import com.salesmanager.web.constants.Constants;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * Used for misc reference objects
 * @author csamson777
 *
 */
@Controller
public class ReferenceController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ReferenceController.class);
	
	@Autowired
	private CacheUtils cache;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value={"/admin/reference/provinces","/shop/reference/provinces"}, method=RequestMethod.POST, produces="application/json;charset=UTF-8")
	public @ResponseBody String getProvinces(HttpServletRequest request, HttpServletResponse response) {
		
		AjaxResponse resp = new AjaxResponse();
		
		try {
			

			resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
		
		} catch (Exception e) {
			LOGGER.error("GetProvinces()", e);
			resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
		}
		
		
		String returnString = resp.toJSONString();
		return returnString;
		
	}


	@SuppressWarnings("unchecked")
	@RequestMapping(value={"/shop/reference/monthsOfYear"}, method=RequestMethod.GET, produces="application/json;charset=UTF-8")
	public @ResponseBody String getMonthsOfYear(HttpServletRequest request, HttpServletResponse response) {
		List<String> days = null;
		String serialized = null;
		
		try {	
			days = (List<String>)cache.getFromCache(Constants.MONTHS_OF_YEAR_CACHE_KEY);
			if(days==null) {

				days = new ArrayList<String>();
				for(int i = 1 ; i < 13 ; i++) {
					days.add(String.format("%02d", i));
				}
				cache.putInCache(Constants.MONTHS_OF_YEAR_CACHE_KEY,days);
			}
			final ObjectMapper mapper = new ObjectMapper();
			serialized = mapper.writeValueAsString(days);
		
		} catch(Exception e) {
			LOGGER.error("ReferenceControler ",e);
		}
		
		return serialized;
	
	}
}
